/*
 * Copyright (c) 2010-2020 Belledonne Communications SARL.
 *
 * This file is part of linphone-android
 * (see https://www.linphone.org).
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package com.newlink.building.activities.main.settings.fragments

import android.content.Context
import android.os.Bundle
import android.view.View
import androidx.core.view.doOnPreDraw
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.NavController
import androidx.navigation.NavDestination
import androidx.navigation.findNavController
import androidx.navigation.fragment.NavHostFragment
import androidx.slidingpanelayout.widget.SlidingPaneLayout
import com.newlink.building.R
import com.newlink.building.activities.*
//import com.vdroid.dooraccess.module_linphone.activities.login.LoginActivity
import com.newlink.building.activities.main.fragments.Module_Phone_SecureFragment
import com.newlink.building.activities.main.settings.Module_Phone_SettingListenerStub
import com.newlink.building.activities.main.settings.viewmodels.Module_Phone_SettingsViewModel
import com.newlink.building.activities.main.viewmodels.Module_Phone_SharedMainViewModel
import com.newlink.building.activities.navigateToAccountSettings
import com.newlink.building.activities.navigateToAudioSettings
import com.newlink.building.activities.navigateToTunnelSettings
import com.newlink.building.activities.navigateToVideoSettings
import com.newlink.building.databinding.SettingsFragmentBinding
import com.newlink.building.utils.Module_Phone_Event
import com.newlink.building.widget.Module_Phone_CustomAlertDialog
import com.google.android.material.transition.MaterialSharedAxis
import com.newlink.building.NL_App.Companion.corePreferences
import org.linphone.core.tools.Log

class Module_Phone_SettingsFragment :
    Module_Phone_SecureFragment<SettingsFragmentBinding>(),
    NavController.OnDestinationChangedListener {
    private lateinit var sharedViewModel: Module_Phone_SharedMainViewModel
    private lateinit var viewModel: Module_Phone_SettingsViewModel

    private var lastClickTime = 0L

    override fun getLayoutId(): Int = R.layout.settings_fragment

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        binding.lifecycleOwner = viewLifecycleOwner

        useMaterialSharedAxisXForwardAnimation = false
        if (corePreferences.enableAnimations) {
            enterTransition = MaterialSharedAxis(MaterialSharedAxis.Z, true)
            reenterTransition = MaterialSharedAxis(MaterialSharedAxis.Z, true)
            returnTransition = MaterialSharedAxis(MaterialSharedAxis.Z, false)
            exitTransition = MaterialSharedAxis(MaterialSharedAxis.Z, false)
        }

        /* Shared view model & sliding pane related */

        sharedViewModel = requireActivity().run {
            ViewModelProvider(this)[Module_Phone_SharedMainViewModel::class.java]
        }

        view.doOnPreDraw {
            sharedViewModel.isSlidingPaneSlideable.value = binding.slidingPane.isSlideable
        }

        // Account settings loading can take some time, so wait until it is ready before opening the pane
        sharedViewModel.accountSettingsFragmentOpenedEvent.observe(
            viewLifecycleOwner
        ) {
            it.consume {
                binding.slidingPane.openPane()
            }
        }

        sharedViewModel.closeSlidingPaneEvent.observe(
            viewLifecycleOwner
        ) {
            it.consume {
                Log.e(
                    "jake",
                    "....closeSlidingPaneEvent.observe...000 ${binding.slidingPane.closePane()}"
                )

//                if (!binding.slidingPane.closePane()) {
//                    Log.e("jake", "....closeSlidingPaneEvent.observe...")
//                    goBack()
//                }
            }
        }
        sharedViewModel.layoutChangedEvent.observe(
            viewLifecycleOwner
        ) {
            it.consume {
                sharedViewModel.isSlidingPaneSlideable.value = binding.slidingPane.isSlideable
                if (binding.slidingPane.isSlideable) {
                    val navHostFragment =
                        childFragmentManager.findFragmentById(R.id.settings_nav_container) as NavHostFragment
                    if (navHostFragment.navController.currentDestination?.id == R.id.emptySettingsFragment) {
                        Log.i("[Settings] Foldable device has been folded, closing side pane with empty fragment")
                        binding.slidingPane.closePane()
                    }
                }
            }
        }
        binding.slidingPane.lockMode = SlidingPaneLayout.LOCK_MODE_LOCKED
        binding.slidingPane.addPanelSlideListener(object : SlidingPaneLayout.PanelSlideListener {
            override fun onPanelSlide(panel: View, slideOffset: Float) {
            }

            override fun onPanelOpened(panel: View) {
            }

            override fun onPanelClosed(panel: View) {
                sharedViewModel.hideNavigationBar.value = false
            }
        })

        /* End of shared view model & sliding pane related */

        viewModel = ViewModelProvider(this)[Module_Phone_SettingsViewModel::class.java]
        binding.viewModel = viewModel

        binding.setBackClickListener { goBack() }

        sharedViewModel.accountRemoved.observe(
            viewLifecycleOwner
        ) {
            Log.i("[Settings] Account removed, update accounts list")
            viewModel.updateAccountsList()
        }

        val identity = arguments?.getString("Identity")
        if (identity != null) {
            Log.i("[Settings] Found identity parameter in arguments: $identity")
            arguments?.clear()
            navigateToAccountSettings(identity)
        }

        viewModel.accountsSettingsListener = object : Module_Phone_SettingListenerStub() {
            override fun onAccountClicked(identity: String) {
                Log.i("[Settings] Navigation to settings for account with identity: $identity")
                if (refuseWhenFastClicked()) return
                navigateToAccountSettings(identity)
            }
        }

        viewModel.tunnelSettingsListener = object : Module_Phone_SettingListenerStub() {
            override fun onClicked() {
                navigateToTunnelSettings(binding.slidingPane)
            }
        }

        viewModel.audioSettingsListener = object : Module_Phone_SettingListenerStub() {
            override fun onClicked() {
                navigateToAudioSettings(binding.slidingPane)
            }
        }

        viewModel.videoSettingsListener = object : Module_Phone_SettingListenerStub() {
            override fun onClicked() {
                navigateToVideoSettings(binding.slidingPane)
            }
        }

        viewModel.callSettingsListener = object : Module_Phone_SettingListenerStub() {
            override fun onClicked() {
                if (refuseWhenFastClicked()) return
                navigateToCallSettings(binding.slidingPane)
            }
        }

        viewModel.chatSettingsListener = object : Module_Phone_SettingListenerStub() {
            override fun onClicked() {
                navigateToChatSettings(binding.slidingPane)
            }
        }

        viewModel.networkSettingsListener = object : Module_Phone_SettingListenerStub() {
            override fun onClicked() {
                if (refuseWhenFastClicked()) return
                navigateToNetworkSettings(binding.slidingPane)
            }
        }

        viewModel.logSettingsListener = object : Module_Phone_SettingListenerStub() {
            override fun onClicked() {
                if (refuseWhenFastClicked()) return
                navigateToLogSettings(binding.slidingPane)
            }
        }

        viewModel.logoutListener = object : Module_Phone_SettingListenerStub() {
            override fun onClicked() {
                sharedViewModel.accountRemoved.value = true
//                startActivity(Intent(context, LoginActivity::class.java))
            }
        }

        viewModel.aboutSettingsListener = object : Module_Phone_SettingListenerStub() {
            override fun onClicked() {
                if (System.currentTimeMillis() - lastClickTime < 800L) {
                    return
                }
                lastClickTime = System.currentTimeMillis()
                navigateToUpdateSettings(binding.slidingPane)
            }
        }

        viewModel.contactsSettingsListener = object : Module_Phone_SettingListenerStub() {
            override fun onClicked() {
                navigateToContactsSettings(binding.slidingPane)
            }
        }

        viewModel.advancedSettingsListener = object : Module_Phone_SettingListenerStub() {
            override fun onClicked() {
                navigateToAdvancedSettings(binding.slidingPane)
            }
        }

        viewModel.logoutSettingsListener = object : Module_Phone_SettingListenerStub() {
            override fun onClicked() {
                showConfirmDialog(context!!)
            }
        }

        viewModel.settingsRemovedEvent.observe(
            viewLifecycleOwner
        ) {

            it.consume { it ->
                if (it) {
                    goBack()
                    sharedViewModel.accountRemoved.value = true
//                    startActivity(Intent(context, LoginActivity::class.java))
                }
            }
        }
    }

    private fun refuseWhenFastClicked(): Boolean {
        if (System.currentTimeMillis() - lastClickTime < 1000L) {
            return true
        }
        lastClickTime = System.currentTimeMillis()
        return false
    }

    override fun onStart() {
        super.onStart()
        binding.settingsNavContainer.findNavController().addOnDestinationChangedListener(this)
    }

    override fun onResume() {
        super.onResume()
        sharedViewModel.hideNavigationBar.value =
            false
    }

    override fun onStop() {
        binding.settingsNavContainer.findNavController().removeOnDestinationChangedListener(this)
        super.onStop()
    }

    fun showConfirmDialog(context: Context) {

        Module_Phone_CustomAlertDialog(context).apply {
            setCheckboxVisible(resources.getString(R.string.dialog_default_delete_record))
            setContentText(resources.getString(R.string.dialog_default_delete_account))
            setPositiveButton(resources.getString(R.string.confirm_dialog_custom)) {
                if (this.isChecked()) {
                    sharedViewModel.refreshDataCommandEvent.value = Module_Phone_Event(true)
                    viewModel.clearRecordsAndHistory()
                }
                this.dismiss()
                viewModel.deleteAccount()
            }
            setNegativeButton(resources.getString(R.string.cancel_dialog_custom)) {
                this.dismiss()
            }
            show()
        }
    }

    override fun onDestinationChanged(
        controller: NavController,
        destination: NavDestination,
        arguments: Bundle?
    ) {
        when (destination.id) {
            R.id.accountSettingsFragment, R.id.callSettingsFragment, R.id.networkSettingsFragment,
            R.id.logSettingsFragment, R.id.aboutSettingsFragment, R.id.updateSettingsFragment ->
                sharedViewModel.hideNavigationBar.value =
                    true
        }
    }
}
